<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +--------------------------------------------------------------
 * | Copyright (c) 2013-2019 http://qxwoo.cn All rights reserved.
 * +--------------------------------------------------------------
 * | y139w <y139w@163.com>
 * +--------------------------------------------------------------
 * | 2019/06/22 03:15:18
 * +--------------------------------------------------------------
 * | Format.php
 * +--------------------------------------------------------------
 */


namespace luo\traits;


trait Format
{

    /**
     * 格式化银行卡号
     * @param $number
     * @param int $length
     * @return string
     */
    public static function bank($number, $length = 4){

        $index = 0;
        $section = [];
        $count = ceil(strlen($number) / $length);
        while($index < $count){
            $section[] = substr($number, $index * $length, $length);
            $index++;
        }
        $number = implode(' ', $section);
        return $number;

    }

    /**
     * 金额格式化
     * @param $number
     * @param int $length
     * @return string
     */
    public static function amount($number, $length = 3){

        $decimal = [];
        if(strpos((string)$number, '.')){
            $numberArray = explode('.', $number);
            $integer = str_split($numberArray[0] ?? 0);
            $decimal = str_split($numberArray[1] ?? 0);
        }else{
            $integer = str_split($number);
        }
        $reverse = array_reverse($integer);
        $index = 1;
        $section = [];
        foreach($reverse as $val){
            $section[] = $val;
            if($index % $length == 0){
                $section[] = ',';
            }
            $index++;
        }
        $number = trim(implode('', [
            implode('', array_reverse($section)),
            implode('', $decimal)
        ]), ',');
        return $number;

    }

    /**
     * 价格格式化
     * @param $number
     * @param null $prefix
     * @param bool $decimal
     * @return string
     */
    public static function price($number, $prefix = null, $decimal = false){

        $section = [];
        if($prefix){
            $section[] = $prefix;
        }
        $fraction = [];
        if(strpos((string)$number, '.')){
            $numberArray = explode('.', (string)$number);
            $integer = $numberArray[0] ?? 0;
            $section[] = $integer;
            $fraction[] = str_split($numberArray[1] ?? 0);
        }else{
            $section[] = $number;
        }
        if($decimal){
            $lack = $decimal - count($fraction);
            while($lack > 0){
                $fraction[] = '0';
                $lack--;
            }
        }
        $section[] = (string)implode('', $fraction);
        return implode('', $section);

    }

}